package com.tegistuff.webos.actions;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.tegistuff.webos.AppComponent;
import com.tegistuff.webos.run.WebOSRunConfiguration;
import com.tegistuff.webos.run.WebOSRunner;

/**
 * BuildAppAction.java
 *
 * Copyright (C) 2012 Timo Tegtmeier.
 * All rights reserved.
 */
public class BuildAppAction extends AnAction {
    @Override
    public void actionPerformed(AnActionEvent event) {
        if(!AppComponent.IsSDKSupported())
            return;

        final Project project = event.getData(PlatformDataKeys.PROJECT);
        if(project == null)
            return;
        final RunManager runManager = RunManager.getInstance(project);
        if(runManager == null)
            return;
        final RunnerAndConfigurationSettings runnerAndConfigurationSettings = runManager.getSelectedConfiguration();
        if(runnerAndConfigurationSettings == null)
            return;
        final RunConfiguration runConfiguration = runnerAndConfigurationSettings.getConfiguration();
        if((runConfiguration == null) || !(runConfiguration instanceof WebOSRunConfiguration))
            return;

        ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
            @Override
            public void run() {
                try {
                    WebOSRunner runner = new WebOSRunner(project, (WebOSRunConfiguration)runConfiguration, WebOSRunner.BuildMode.BUILD_ONLY);
                    OSProcessHandler processHandler = runner.getProcessHandler();
                    processHandler.startNotify();
                    processHandler.waitFor();
                    if(processHandler.getProcess().exitValue() != 0)
                        throw new ExecutionException("Building failed.");
                } catch (final Exception e) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        public void run() {
                            Messages.showErrorDialog(project, "Cannot build app package:\n" + e.getMessage(), "Error");
                        }
                    });
                }
            }
        }, "Building webOS application", false, project);

    }
}
